package com.video.main_video.manager.handle.uploadFile;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.video.main_video.api.Api;
import com.video.main_video.common.utils.ImgUtils;
import com.video.main_video.dao.entity.VideoInfo;
import com.video.main_video.dao.request.videoUpdate.VideoUploadRequest;
import com.video.main_video.dao.response.videoUpdate.VideoUploadResponse;
import com.video.main_video.manager.handle.ApiHandler;
import com.video.main_video.manager.mapper.VideoInfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.*;


@Api
public class UpdateVideoManager implements ApiHandler<VideoUploadRequest, VideoUploadResponse> {

    @Autowired
    VideoInfoMapper videoInfoMapper;

    @Override
    public VideoUploadResponse handler(VideoUploadRequest videoUploadRequest) {
        VideoUploadResponse res = new VideoUploadResponse();
        res.setCode(200);
        boolean result = updateVideoInfo(videoUploadRequest);
        if (!result) {
            res.setCode(1002);
        }
        return res;
    }

    private boolean updateVideoInfo(VideoUploadRequest req) {
        VideoInfo videoInfo = new VideoInfo();
        BeanUtils.copyProperties(req, videoInfo);
        LambdaQueryWrapper<VideoInfo> qw = new LambdaQueryWrapper<>();
        qw.eq(VideoInfo::getCutId, req.getCutId());
        VideoInfo info = videoInfoMapper.selectOne(qw);
        videoInfo.setId(info.getId());
        String fileName = "";
        try {
            fileName = ImgUtils.base64toPng(req.getVideoImage(), info.getUserId());
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        videoInfo.setVideoImage(fileName);
        videoInfoMapper.updateById(videoInfo);
        return true;
    }
}
